<?php

namespace app\admin\controller\tree\config;

use app\BaseController;
use app\common\service\TreeSensitiveFilterService;
use app\model\tree\TreeSensitiveWordsModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;

class SensitiveWords extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 敏感词列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            $TreeSensitiveWordsModel = new TreeSensitiveWordsModel();
            $query = $TreeSensitiveWordsModel->where($where);
            $data = $query->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 敏感词添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'name|敏感词' => 'require',
                'status|状态' => 'require|in:0,1',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $TreeSensitiveWordsModel = new TreeSensitiveWordsModel();
            $TreeSensitiveWordsModel->insert($param);
            $this->updateSensitiveWord();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 敏感词编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|敏感词' => 'require',
                'status|状态' => 'require|in:0,1',
            ]);
            $TreeSensitiveWordsModel = new TreeSensitiveWordsModel();
            $info = $TreeSensitiveWordsModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save($param);
            $this->updateSensitiveWord();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 敏感词删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TreeSensitiveWordsModel = new TreeSensitiveWordsModel();
            if (is_array($param['id'])) {
                $TreeSensitiveWordsModel->where('id', 'in', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }else{
                $info = $TreeSensitiveWordsModel->find($param['id']);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            $this->updateSensitiveWord();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 更新词库
     * @return void
     */
    public function updateSensitiveWord(): void
    {
        $TreeSensitiveFilterService = new TreeSensitiveFilterService($this->app);
        $TreeSensitiveFilterService->refreshCache($this->userData['unit_id']);
    }

    /**
     * 导入
     * @return bool|string
     */
    public function import(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'file' => 'require'
            ]);
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($param['file']))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 2) throw new \Exception('请填写导入的内容！');
            $data = $sheet->rangeToArray('A2:A'.$limit,'', true, true);
            $addData = [];
            foreach ($data as $v) {
                if (empty($v)) continue;
                $addData[] = [
                    'unit_id' => $this->userData['unit_id'],
                    'name' => $v[0],
                    'time' => time()
                ];
            }
            $TreeSensitiveWordsModel = new TreeSensitiveWordsModel();
            $TreeSensitiveWordsModel->insertAll($addData);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}